#include <REGX52.H>
sbit DS1302_SCLK=P3^6;
sbit DS1302_CE=P3^5;
sbit DS1302_I0=P3^4;

#define DS1302_SEC    	0x80
#define DS1302_MIN     	0x82
#define DS1302_HOUR     0x84
#define DS1302_DATA     0x86
#define DS1302_MON     	0x88
#define DS1302_DAY     	0x8A
#define DS1302_YEAR     0x8C
#define DS1302_WP     	0x8E

char DS1302_TIME[]={22,8,12,17,59,59,5};
void DS1302_INIT()
{
	DS1302_CE=0;
	DS1302_SCLK=0;

}

void DS1302_WRITE(unsigned char commond, Data)
{
	unsigned char i=0;
	DS1302_CE=1;
	
	for(i=0;i<8;i++)
	{
	  DS1302_I0=commond&(0x01<<i);
		DS1302_SCLK=1;
		DS1302_SCLK=0;
	}
	for(i=0;i<8;i++)
	{
	  DS1302_I0=Data&(0x01<<i);
		DS1302_SCLK=1;
		DS1302_SCLK=0;
	}
	DS1302_CE=0;
}
unsigned char DS1302_READ(unsigned char commond)
{	
	unsigned char i=0,Data=0x00;
	commond|=0x01;
	
	DS1302_CE=1;

	for(i=0;i<8;i++)
	{
	  DS1302_I0=commond&(0x01<<i);
		DS1302_SCLK=0;
		DS1302_SCLK=1;
	} 
	for(i=0;i<8;i++)
	{
		DS1302_SCLK=1;
		DS1302_SCLK=0;
		if(DS1302_I0)
		{
			Data=Data|(0x01<<i);
		}
	}
	DS1302_CE=0;
	DS1302_I0=0;
	return Data;
}
void DS1302_SETTIME()
{
	DS1302_WRITE(DS1302_WP,0x00);
	DS1302_WRITE(DS1302_YEAR,DS1302_TIME[0]/10*16+DS1302_TIME[0]%10);
	DS1302_WRITE(DS1302_MON,DS1302_TIME[1]/10*16+DS1302_TIME[1]%10);
	DS1302_WRITE(DS1302_DATA,DS1302_TIME[2]/10*16+DS1302_TIME[2]%10);
	DS1302_WRITE(DS1302_HOUR,DS1302_TIME[3]/10*16+DS1302_TIME[3]%10);
	DS1302_WRITE(DS1302_MIN,DS1302_TIME[4]/10*16+DS1302_TIME[4]%10);
	DS1302_WRITE(DS1302_SEC,DS1302_TIME[5]/10*16+DS1302_TIME[5]%10);
    DS1302_WRITE(DS1302_DAY,DS1302_TIME[6]/10*16+DS1302_TIME[6]%10);
//	DS1302_WRITE(DS1302_WP,0x80);
}
void DS1302_READTIME()
{
	unsigned char  TAM=0;
	TAM=DS1302_READ(DS1302_YEAR);
	DS1302_TIME[0]=TAM/16*10+TAM%16;
	TAM=DS1302_READ(DS1302_MON);
	DS1302_TIME[1]=TAM/16*10+TAM%16;
	TAM=DS1302_READ(DS1302_DATA);
	DS1302_TIME[2]=TAM/16*10+TAM%16;
	TAM=DS1302_READ(DS1302_HOUR);
	DS1302_TIME[3]=TAM/16*10+TAM%16;
	TAM=DS1302_READ(DS1302_MIN);
	DS1302_TIME[4]=TAM/16*10+TAM%16;
	TAM=DS1302_READ(DS1302_SEC);
	DS1302_TIME[5]=TAM/16*10+TAM%16;
	TAM=DS1302_READ(DS1302_DAY);
	DS1302_TIME[6]=TAM/16*10+TAM%16;
	
		
}